package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
*
* 拦截器，用于验证token
* */
public class WmTokenInterception implements HandlerInterceptor {


    /*
     *
     * 拦截header中的用户信息，存入到当前线程
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("id1");
        if(!StringUtils.isEmpty(userId)){
            //将用户id存入到当前线程
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtil.setUser(wmUser);
        }

        return true;
    }


    /*
     *
     * 拦截header中的用户信息，存入到当前线程
     * */
   @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //清除用户信息
       WmThreadLocalUtil.clear();
    }
}
